<template>
  <view>
    <view class="d-flex gm-tab">
      <view @click="setLabel(item)" :class="{'active': item.value == itemIndex}" class="gm-tab_li" v-for="(item,index) in items" :key="index">
        {{ item.name }}
      </view>
    </view>
    <wd-gap height="1rem"></wd-gap>
    <scroll-view class="scroll-view" scroll-y>
      <view v-for="(item,index) in rings" :key="index" class="classify-li">
        <view class="audio-pos">
          <view v-if="item.association == audioUrl" class="audio-icon" @click="stopAudio">
            <wd-icon color="#fff" name="pause-circle" size="30px"></wd-icon>
          </view>
          <image @click="setAudio(item)" style="width: 70px; border-radius: 10px;" mode="widthFix" :src="item.url"/>
        </view>
        <view style="margin-left: 0.5rem;" class="flex-1 classify-column">
          <view style="font-size: 0.95rem;">{{item.name}}</view>
          <view class="d-flex" style="margin: 0.15rem 0;">
            <view>
              <wd-tag custom-class="space" type="danger">hot</wd-tag>
            </view>
            <view style="margin: 0 0.3rem;">
              <image style="width: 11px;" mode="widthFix" src="/static/assets/images/erji.png"></image>
            </view>
            <view>{{item.likes}}次</view>
            <view class="classify-point"></view>
            <view>{{item.author}}</view>
          </view>
          <view>{{item.tip}}</view>
        </view>
        <wd-button @click="saveRing(item)" plain size="small">设铃声</wd-button>
      </view>
    </scroll-view>
    <!-- <x-adudio-play v-if="audioUrl" :url='audioUrl'></x-adudio-play> -->
  </view>
  
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { onLoad, onPullDownRefresh, onShow, onReachBottom, onUnload } from "@dcloudio/uni-app";
const rings = ref([])
const audioRef = ref(null), audioUrl = ref(null)
const page = ref(1), isPullDownRefresh = ref(false);
import { innerAudioContext } from '@/hooks/utils'
import store from '../../store';
const type = ref('hot')
onMounted(() => {
  getRings()
  // if (!innerAudioContext) {
  //   innerAudioContext.autoplay = true
  // }
})
const userInfo = computed(()=>{
	return store.state.value.userInfo
})
const getRings = () => {
  uni.showToast({
    title: '加载中',
    icon: 'loading',
    duration: 1500
  })
  uni.request({
    url: `/api/wallpaper/oss/page?size=20&page=${page.value}&type=` + type.value,
    method: 'GET',
    success: (res) => {
      res.data.data.forEach((item) => {
        item.image = item.url;
      });
      rings.value = rings.value.concat(res.data.data)
      uni.hideToast()
    }
  })
}

onUnload(() => {
  innerAudioContext && innerAudioContext.pause()
})

const itemIndex = ref('hot')
const items = ref([
  {
    name: '最热',
    value: 'hot',
  },
  {
    name: '抖音',
    value: 'douyin',
  },
  {
    name: '最新',
    value: 'new',
  },
  {
    name: '分类',
    value: 'kind',
  }
])
const setAudio = (item) => {
  audioUrl.value = item.association
  innerAudioContext.src = decodeURIComponent(item.association)
  
  innerAudioContext.onEnded(() => {
 //    audioUrl.value = null;
	setTimeout(() => {
	        // 等待2秒后重新播放音频
	        innerAudioContext.play();
	    }, 2000);
  });
  
  innerAudioContext.play()
  uni.request({
    url: '/api/wallpaper/oss/ring',
    method: 'POST',
    data: {
      url: item.url
    },
    success: (res) => {
      item.likes = res.data.likes
    }
  })
}
const stopAudio = () => {
  innerAudioContext.pause()
  audioUrl.value = null
}
const setLabel = (item) => {
  if(innerAudioContext){
    innerAudioContext.pause()
    audioUrl.value = null
  }
  itemIndex.value = item.value
  type.value = item.value
  page.value = 1
  uni.request({
    url: `/api/wallpaper/oss/page?size=20&page=${page.value}&type=` + type.value,
    method: 'GET',
    success: (res) => {
      res.data.data.forEach((item) => {
        item.image = item.url;
      });
      rings.value = res.data.data
      uni.hideToast()
    }
  })
}
const saveRing = (item) => {
  const username = uni.getStorageSync("wpa_username");
  if (!username) {
    uni.showModal({
      title: "提示",
      content: "请先登录,才能下载壁纸",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: "/pages/login/index",
          });
        }
      },
    });
    return;
  }
  if( !userInfo.value.vip ){
    uni.showToast({
      title: "VIP专享,您要先开通VIP才能下载",
      icon: "none",
    });
    return;
  }
  // #ifdef APP-PLUS
  return handleSetRing(item)
  // #endif
  uni.showToast({
    title: '保存中',
    icon: 'loading',
    duration: 6000
  })
  uni.downloadFile({
    url: item.association,
    success: (res) => {
      // console.log(res);
			// #ifndef H5
			if (plus.os.name.toLowerCase() === "android") {
				var filePath = res.tempFilePath.replace("file://", "");
				setSystemRing(filePath);
			}
			// #endif
      uni.saveVideoToPhotosAlbum({
        filePath: res.tempFilePath,
        success: (res) => {
          uni.showToast({
            title: "保存成功",
            icon: "none",
          });
        },
        fail: (res) => {
          console.log(res);
        },
      });
    },
  });
}
const setSystemRing = (path) => {
	plus.android.importClass(path);
	  var Context = plus.android.importClass("android.content.Context");
	  var RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
	  var Uri = plus.android.importClass("android.net.Uri");
	  var file = new plus.android.invoke('java.io.File', path);
	  var ringUri = Uri.parse(plus.android.invoke('android.provider.MediaStore$Audio$Media', 'getContentUri', 'external'));
	  var main = plus.android.runtimeMainActivity();
	  var cursor = main.getContentResolver().query(ringUri, null, null, null, null);
	  var ringtone = RingtoneManager.getRingtone(main, Uri.parse(file.getAbsolutePath()));
	  ringtone.setType(RingtoneManager.TYPE_RINGTONE);
	  ringtone.setTitle("Custom Ringtone");
	  var contentValues = new plus.android.invoke('android.content.ContentValues');
	  contentValues.put("title", "Custom Ringtone");
	  contentValues.put("ringtone_type", RingtoneManager.TYPE_RINGTONE);
	  contentValues.put("data", file.getAbsolutePath());
	  var newUri = main.getContentResolver().insert(RingtoneManager.getDefaultType(RingtoneManager.TYPE_RINGTONE), contentValues);
	  RingtoneManager.setActualDefaultRingtoneUri(main, RingtoneManager.TYPE_RINGTONE, newUri);
	  plus.android.invoke('android.media.RingtoneManager', 'setActualDefaultRingtoneUri', main, RingtoneManager.TYPE_RINGTONE, newUri);
}
onReachBottom(() => {
  page.value++;
  isPullDownRefresh.value = false;
  getRings();
})

const resolveLocalFileSystemURL = (tempFilePath) => {
	return new Promise((resolve,reject)=>{
		plus.io.resolveLocalFileSystemURL(tempFilePath,
		  (entry) => {
			console.log('resolveLocalFileSystemURL 成功:', entry.fullPath);
			resolve(entry.fullPath);
			
		  },
		  (error) => {
			console.error('resolveLocalFileSystemURL 失败:', error);
			reject(error);
		  }
		);
	})
}

const setAppSystemRing = async (audioInfo, ringType = 1) => {
  // #ifdef APP-PLUS
  if (plus.os.name.toLowerCase() !== 'android') {
    uni.showToast({
      title: '仅支持安卓设备',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: '设置中...'
    });

    // 1. 检查权限
    const main = plus.android.runtimeMainActivity();
    const Settings = plus.android.importClass("android.provider.Settings");
    const Uri = plus.android.importClass("android.net.Uri");
    const Intent = plus.android.importClass("android.content.Intent");
    
    if (!Settings.System.canWrite(main)) {
      uni.hideLoading();
      uni.showModal({
        title: '需要权限',
        content: '设置铃声需要修改系统设置权限，请在接下来的页面中开启权限',
        success: function (res) {
          if (res.confirm) {
           const permissions = ['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE','android.permission.WRITE_SETTINGS'];
           plus.android.requestPermissions(permissions, function (result) {
               if (result.denied.length > 0) {
                   console.log("用户拒绝了权限");
               } else {
                   console.log("权限已授予");
               }
           });
            
            uni.showToast({
              title: '请开启权限后重试',
              icon: 'none',
              duration: 3000
            });
          }
        }
      });
      return;
    }

    // 2. 下载文件
    const downloadResult = await uni.downloadFile({
      url: decodeURIComponent(audioInfo.association)
    });
	if (downloadResult.statusCode !== 200) {
	  throw new Error('下载文件失败');
	}
	console.log('tempFilePath',downloadResult.tempFilePath)

    // 3. 导入所需的类
    const File = plus.android.importClass("java.io.File");
    const Environment = plus.android.importClass("android.os.Environment");
    const FileInputStream = plus.android.importClass("java.io.FileInputStream");
    const FileOutputStream = plus.android.importClass("java.io.FileOutputStream");
    const FileChannel = plus.android.importClass("java.nio.channels.FileChannel");

    // 4. 准备目标文件夹和文件
    const externalStorage = Environment.getExternalStorageDirectory();
    const ringtoneDir = new File(externalStorage, "Ringtones");
    if (!ringtoneDir.exists()) {
      const success = ringtoneDir.mkdirs();
      if (!success) {
        throw new Error('创建铃声目录失败');
      }
    }
    const fileName = "bzkk_" + audioInfo.name + ".mp3";
    let isExists = false;
    const files = ringtoneDir.listFiles();
    for (const file of files) {
      if (file.getName() === fileName) {
        isExists = true
        break;
      }
    }
    const destFile = new File(ringtoneDir, fileName);

    if(!isExists){
      // 5. 复制文件到铃声目录
        
      const resolvePath = await resolveLocalFileSystemURL(downloadResult.tempFilePath)
        const sourceFile = new File(resolvePath);
      
      if (sourceFile.exists()) {
          console.log("文件存在，长度为:", sourceFile.length());
      } else {
          console.log("文件不存在");
      }
    
        // 4. 使用 FileChannel 复制文件
      const inputStream = new FileInputStream(sourceFile);
      const outputStream = new FileOutputStream(destFile);
      
      const inputChannel = inputStream.getChannel();
      const outputChannel = outputStream.getChannel();

      // 使用 transferFrom 复制全部内容
      const sourceSize = sourceFile.length();
      outputChannel.transferFrom(inputChannel, 0, sourceSize);

      // 确保写入完成
      outputChannel.force(true);

      // 关闭通道和流
      inputChannel.close();
      outputChannel.close();
      inputStream.close();
      outputStream.close();
     
    }
     // 5. 验证复制结果
    if (!destFile.exists()) {
        throw new Error('目标文件不存在');
    }

    // 6. 创建文件的 Uri
    const fileUri = Uri.fromFile(destFile);

    // 7. 根据类型设置铃声
    let settingName;
    switch (ringType) {
      case 1:
        settingName = Settings.System.RINGTONE;
        break;
      case 2:
        settingName = Settings.System.NOTIFICATION_SOUND;
        break;
      case 3:
        settingName = Settings.System.ALARM_ALERT;
        break;
    }

    // 8. 设置铃声
    Settings.System.putString(main.getContentResolver(), settingName, fileUri.toString());

    // 9. 通知系统更新媒体库
    const intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(fileUri);
    main.sendBroadcast(intent);

    uni.showToast({
      title: '设置成功',
      icon: 'success'
    });

  } catch (error) {
    console.error('设置铃声失败:', error);
    uni.showToast({
      title: error.message || '设置失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
  // #endif
}

// 修改 handleSetRing 方法，增加权限检查
const handleSetRing = (item) => {
  // 显示铃声类型选择
  uni.showActionSheet({
    itemList: ['设为来电铃声', '设为通知铃声', '设为闹钟铃声'],
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
            setAppSystemRing(item, 1);
          break;
        case 1:
            setAppSystemRing(item, 2);
          break;
        case 2:
            setAppSystemRing(item, 3);
          break;
      }
    }
  });
}
</script>

<style lang="scss" scoped>
.classify-li{
  display: flex;
  align-items: center;
  --wot-button-small-fs: 0.8rem;
  --wot-color-white: rgb(243, 228, 239);
  --wot-color-theme: rgb(224, 100, 127);
  margin-bottom: 1.1rem;
  .classify-column{
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 0.8rem;
  }
  .classify-point{
    margin: 0 0.2rem;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: #222;
  }
}
.gm-fix{
  position: absolute;
  top: 10px;
  right: 10px;
}
.gm-tab_li{
  color: rgba(144, 144, 144, 1);
  font-size: 0.9rem;
}
.gm-tab{
  display: grid;
  grid-template-columns: repeat(auto-fill, 50px);
  grid-gap: 10px;
  .active{
    color: rgba(220, 70, 129, 1);
  }
}
.audio-pos{
  position: relative
}
.audio-icon{
  position: absolute;
  left: 0;
  top: 0;
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}
</style>